package com.hqy.hb.web;


import com.hqy.webmvc.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import java.io.File;

/**
 * @Author hqy
 * @Date 2022/5/15
 * @Description
 */
public final class HBWebApplication{

    private Context context;
    private WebResourceRoot webResourceRoot;
    private Tomcat tomcat;

    public static void run(Class<?> clazz,String[] args){
        HBWebApplication app = new HBWebApplication();
        app.start(clazz,args);
    }

    private void start(Class<?> clazz,String[] args){
        try {
            //创建内嵌Tomcat
            tomcat = new Tomcat();
            tomcat.setPort(8080);
            tomcat.getConnector();
            tomcat.setBaseDir(".");
            //将当前应用部署至tomcat
            context = tomcat.addWebapp("/T",
                    new File(clazz.getResource("/").getPath()).getAbsolutePath());
            webResourceRoot = new StandardRoot(context);
            //挂载class文件
            webResourceRoot.addPreResources(
                    new DirResourceSet(webResourceRoot, "/WEB-INF/classes",
                            new File(clazz.getResource("/").getPath()).getAbsolutePath(), "/"));
            context.setResources(webResourceRoot);
            //载入分发器
            tomcat.addServlet("/T", "DispatcherServlet", new DispatcherServlet());
            context.addServletMappingDecoded("/*", "DispatcherServlet");
            //启动
            tomcat.start();
            tomcat.getServer().await();

        } catch (Exception e) {
            throw new Error("Tomcat启动失败，原因："+e);

        }
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public WebResourceRoot getWebResourceRoot() {
        return webResourceRoot;
    }

    public void setWebResourceRoot(WebResourceRoot webResourceRoot) {
        this.webResourceRoot = webResourceRoot;
    }

    public Tomcat getTomcat() {
        return tomcat;
    }

    public void setTomcat(Tomcat tomcat) {
        this.tomcat = tomcat;
    }
}